package com.it.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.bean.Role;
import com.it.dto.RoleDTO;
import com.it.mapper.RoleMapper;
import com.it.page.PageQuery;
import com.it.service.RoleService;
import com.it.utils.AppUtils;
import com.it.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("roleService")
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
    private final RoleMapper roleMapper;

    @Override
    public PageInfo<RoleVo> page(PageQuery<RoleDTO> pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize());
        List<RoleVo> roles = roleMapper.selectJoin(pageQuery.getQueryBody());
        return new PageInfo<>(roles);
    }

    @Override
    public List<Role> list(Role role) {
        role.setDeleted(false);
        return roleMapper.select(role);
    }

    @Override
    public void save(Role role) {
        if (role.getId() == null) {
            AppUtils.forSaveAudit(role);
            roleMapper.save(role);
        } else {
            AppUtils.forUpdateAudit(role);
            roleMapper.updateByPrimaryKeySelective(role);
        }
    }

    @Override
    public void delete(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        role.setDeleted(true);
        AppUtils.forUpdateAudit(role);
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void authorized(Long roleId, List<Long> menuIds) {
        //先删除权限 再新增
        roleMapper.deleteRoleMenu(roleId);
        roleMapper.insertRoleMenuIds(roleId,menuIds);
    }

    @Override
    public List<Long> auths(Long roleId) {
        return roleMapper.auths(roleId);
    }
}
